package com.starhub.api.document.token;

import org.springframework.stereotype.Component;

import com.starhub.common.sys.user.LoginUser;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.UUID;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**   
 * 下载token管理
 * @version: V1.0
 * @author: liuhf
 * @time 2025-05-22
 */
@Component
public class DownloadTokenManager {
    private final Map<String, DownloadToken> tokenCache = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public DownloadTokenManager() {
        // 启动定时清理任务
        scheduler.scheduleAtFixedRate(this::cleanExpiredTokens, 1, 1, TimeUnit.MINUTES);
    }

    public String generateToken(Long fileId, LoginUser user) {
        String token = UUID.randomUUID().toString();
        DownloadToken downloadToken = new DownloadToken(fileId, user, LocalDateTime.now().plusMinutes(10));
        tokenCache.put(token, downloadToken);
        return token;
    }

    public DownloadToken validateToken(String token) {
        DownloadToken downloadToken = tokenCache.get(token);
        if (downloadToken != null && !downloadToken.isExpired()) {
            return downloadToken;
        }
        return null;
    }

    private void cleanExpiredTokens() {
        tokenCache.entrySet().removeIf(entry -> entry.getValue().isExpired());
    }

    public void removeToken(String token) {
        tokenCache.remove(token);
    }
} 